package com.example.wj.controller;

import com.example.wj.utils.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Objects;

@CrossOrigin
@RestController
@RequestMapping("/library")
public class LibraryController {

    @PostMapping("/covers")
    public String coversUpload(MultipartFile file) {
        String folder = "D:/template/imageFile";
        File imageFolder = new File(folder);

        File f = new File(imageFolder,
                StringUtils.getRandomString(6) + Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().length() - 4));

        try {
            file.transferTo(f);
            String imgURL = "http://localhost:8805/library/covers/" + f.getName();
            return imgURL;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }
}
